package com.example.demomk.Repository;

import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.pdf.PdfDocument;
import android.icu.text.SimpleDateFormat;
import android.util.Log;

import androidx.core.content.ContextCompat;

import com.example.demomk.R;
import com.example.demomk.Utils.PDFPageBuilder;
import com.example.demomk.Utils.StdDialogData;
import com.example.demomk.Utils.TimeUtils;
import com.example.demomk.db.AppDatabase;
import com.example.demomk.entity.AvgMeasurement;
import com.example.demomk.entity.AvgMeasurementWithMeasurements;
import com.example.demomk.entity.LocationStats;
import com.example.demomk.entity.Measurement;
import com.example.demomk.entity.SizeStats;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public class printRepository {
    private final AppDatabase database;
    private String timestamp;
    private  String currentTime;


    public printRepository(Application application) {
        this.database = AppDatabase.getInstance(application); // 或通过构造函数传入
    }

    // 生成 PDF 文件的主逻辑
    public void generatePDF(Context context, String title, int avgId, OnPDFGeneratedListener listener, Typeface font, StdDialogData data,List<SizeStats> sizeStats,List<LocationStats> locationStats) {
        // 1. 获取数据
        AvgMeasurementWithMeasurements avgMeasure = database.avgMeasurementDao().getAvgNotLiveDetails(avgId);



        currentTime = TimeUtils.getCurrentTime();
        if (avgMeasure == null ) {
            listener.onError(new Exception("数据加载失败"));
            return;
        }

        // 2. 执行绘制逻辑
        File file = printPDF(context, title, avgMeasure,  font,data, sizeStats,locationStats);

        if (file != null) {
            listener.onSuccess(file);
        } else {
            listener.onError(new Exception("生成 PDF 失败"));
        }
    }

    // 将原来的 printPDF 方法移到这里
    private File printPDF(Context context, String title, AvgMeasurementWithMeasurements avgMeasure, Typeface font,StdDialogData data ,List<SizeStats> stats,List<LocationStats> locationStats) {
        PdfDocument document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(595, 842, 1).create();
        PdfDocument.Page page = document.startPage(pageInfo);
        Canvas canvas = page.getCanvas();
        int currentpage = 1;
//        int total = 2;
        // 2. 跟踪当前Y坐标位置
        float currentY = 0;
        float v = drawHeader(context, canvas, pageInfo, currentY, font);
        float v1 = drawReportTitle(canvas, v, font, data, avgMeasure);
        float v2 = drawStatsTable(canvas, v1, avgMeasure, stats, font, locationStats);
        drawpagefooter(canvas,pageInfo, avgMeasure,currentpage);

        document.finishPage(page);

        // 第二页
        PdfDocument.PageInfo pageInfo2 = new PdfDocument.PageInfo.Builder(595, 842, 2).create();
        PdfDocument.Page page2 = document.startPage(pageInfo2);
        Canvas canvas2 = page2.getCanvas();
        currentpage = currentpage +1;
        float currentY2 = 0;
        float second1 = drawHeader(context, canvas2, pageInfo2, currentY2, font);
        drawDetailsTable(canvas2,second1, avgMeasure, font);
        drawpagefooter(canvas2,pageInfo2, avgMeasure,currentpage);


        document.finishPage(page2);

        //导出文件的名字
        timestamp = TimeUtils.formatTimeString(avgMeasure.avgMeasurement.getStartTime());
        String  fileName = "Standard Report_A2400074_"  + avgMeasure.location.getName() + "_"+ timestamp+".pdf";
        File file = new File(context.getExternalFilesDir(null), fileName);

        try {
            document.writeTo(new FileOutputStream(file));
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            document.close();
        }
    }
    //表格数据
    private float drawStatsTable(Canvas canvas, float startY, AvgMeasurementWithMeasurements avgMeasure, List<SizeStats> statsList ,Typeface font ,List<LocationStats> locationStats) {
        Paint paint = createPaint(8, Color.BLACK, false);
        paint.setTypeface(font);

        // 表格标题
        String[] headerTitles = {"方法", "位点数/区域", "位点数/样本", "总样本数", "采样体积", "采样时间"};
        float[] columnWidths = {75, 75, 75, 90, 90, 90}; // 每列的宽度

        paint.setColor(0xFFF2F2F2);
        canvas.drawRect(50, startY, 50 + sum(columnWidths), startY + 19, paint); // 画表头背景
        // 表头文本颜色
        paint.setColor(Color.BLACK);

        PDFPageBuilder pdfPageBuilder = new PDFPageBuilder(canvas, paint);
        String[][] thresholdData = {
                {"最小值", "8", "1", "8", "23.8", "00:01:00"},
                {"实际值", String.valueOf(statsList.size()), String.valueOf(statsList.size()), String.valueOf(avgMeasure.measurements.size()), avgMeasure.avgMeasurement.getFlow() +"", "00:01:00"}
        };

        float y = pdfPageBuilder.drawTable(50, startY, headerTitles, thresholdData, columnWidths);

        paint.setTypeface(Typeface.create(font, Typeface.ITALIC));
        paint.setTextSize(8);
        canvas.drawText("注意:    采样时间和体积的实际值取所有循环中的最小值。",50,  y+ 15, paint);

        paint.setFakeBoldText(true);
        paint.setTypeface(Typeface.create(font, Typeface.NORMAL));

        paint.setTextSize(10);
        //粒子数据
        canvas.drawText("粒子数据",50,  y+ 35, paint);

        canvas.drawText("计数单位  ∑/m³",295,  y+ 35, paint);

        String[] SizeTitle = {"粒径", "浓度限制", "MAX", "平均值"};
        float[] SizeWidths = {80, 80, 80, 80}; // 每列的宽度
        paint.setColor(0xFFF2F2F2);
        y = y+42;
        canvas.drawRect(50, y, 50 + sum(SizeWidths), y + 19, paint); // 画表头背景
        //statsList是存储各个粒径的集合
        String[][] SizeData = {
                {"0.5μm", "3520.0", statsList.get(0).getMax()+"", statsList.get(0).getAvg()+""}
        };

        paint.setTextSize(8);
        paint.setColor(Color.BLACK);
        float SizeTableHeight = pdfPageBuilder.drawTable(50, y, SizeTitle, SizeData, SizeWidths);

        paint.setTextSize(10);
        paint.setFakeBoldText(true);
        y = SizeTableHeight+20;

        //位点平均值
        canvas.drawText("位点平均值",50,  y+2 , paint);
        canvas.drawText("计数单位  ∑/m³",215,  y+2, paint);
        y= y+10;
        String[] LocTitle = {"位点", "样本数", "0.5μm"};
        float[] LocWidths = {80, 80, 80}; // 每列的宽度
        paint.setColor(0xFFF2F2F2);
        canvas.drawRect(50, y, 50 + sum(LocWidths), y + 19, paint); // 画表头背景
        String[][] loctionStatsTable = getLoctionStatsTable(locationStats);
        paint.setTextSize(8);
        paint.setColor(Color.BLACK);

        float LocTableHeight = pdfPageBuilder.drawTable(50, y , LocTitle, loctionStatsTable, LocWidths);
        y = LocTableHeight + 10;
        return  y;
    };

    //绘制页脚
    private void drawpagefooter(Canvas canvas,PdfDocument.PageInfo pageInfo,AvgMeasurementWithMeasurements avgMeasure,int currentPage) {
        Paint paint = createPaint(10, Color.BLACK, false);
        paint.setTextSize(10);


        float textHeight = pageInfo.getPageHeight() - 60;
        float Signature = textHeight - 20;
        canvas.drawText("操作员:", 270, Signature, paint);
        canvas.drawLine(315, Signature, 395, Signature , paint);

        canvas.drawText("审核员:", 420, Signature , paint);
        canvas.drawLine(465, Signature , 550, Signature , paint);

        canvas.drawLine(50, textHeight, 550, textHeight, paint);

        String create =  "Created by:  "+ avgMeasure.user.getName() + "   "+currentTime;
        canvas.drawText(create, 50, textHeight+15, paint);

        String text = "page: " + currentPage  ;
        float textWidth = paint.measureText(text);
        float textX = pageInfo.getPageWidth() - 50 - textWidth;
        canvas.drawText(text, textX, textHeight+15, paint);
    }
    //绘制详细数据
    private float drawDetailsTable(Canvas canvas, float startY,AvgMeasurementWithMeasurements avgMeasure,Typeface font) {
        Paint paint = createPaint(10, Color.BLACK, false);
        paint.setTypeface(font);
        paint.setFakeBoldText(true);
        paint.setTextSize(10);
        paint.setFakeBoldText(true);

        canvas.drawText("详细数据", 50, startY + 15, paint);

        paint.setTextSize(8);
        float y = startY;
        //时间范围
        //avgMeasure.avgMeasurement.getStartTime() 加一分钟
        String dateStr = avgMeasure.avgMeasurement.getStartTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        paint.setFakeBoldText(false);
        String text = "计数单位  ∑/m³";
        float textWidth = paint.measureText(text);
        float textX = 545 - textWidth;
        try {
            Date date = sdf.parse(dateStr); // 可能抛出 ParseException
            // 使用 Calendar 增加一分钟
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.MINUTE, 1); // 加1分钟
            // 格式化回字符串
            String newDateStr = sdf.format(calendar.getTime());

            canvas.drawText("时间范围：" + dateStr + " ~ " + newDateStr, 50, startY + 30, paint);
        } catch (ParseException e) {
            System.err.println("日期格式错误！请使用 yyyy-MM-dd HH:mm:ss 格式");
            e.printStackTrace();
        }
        canvas.drawText("计数单位  ∑/m³", textX , startY + 30, paint);

        y = startY + 40;

        float[] CountWidths = {25, 25, 50, 50, 40, 50, 55, 50, 50, 50, 50}; // 每列的宽度
        paint.setColor(0xFFF2F2F2);
        canvas.drawRect(50, y, 50 + sum(CountWidths), y + 19, paint); // 画表头背景
        // 表格标题
        String[] headerCountTitle = {"编号", "ID", "起始时间", "位点", "体积", "0.5μm", "1.0μm", "2.0μm", "3.0μm", "5.0μm", "10μm"};
        //详细数据
        String[][] testdata = getTableDataFromMeasurements(avgMeasure.measurements);
        paint.setColor(Color.BLACK);
        PDFPageBuilder pdfPageBuilder = new PDFPageBuilder(canvas,  paint);
        //开始画表格
        float v1 = pdfPageBuilder.drawTable(50, y, headerCountTitle, testdata, CountWidths);
        y = v1 +10;
        return y;
    }

    //获取所有测试的数据
    private String[][] getTableDataFromMeasurements(List<Measurement> measurements) {
        if(measurements == null){
            return new String[0][0];
        }
        String[][] tableData = new String[measurements.size()][11];
        for (int i = 0; i < measurements.size(); i++) {
            Measurement data = measurements.get(i);
            tableData[i][0] = String.valueOf(i+1);
            tableData[i][1] =  String.valueOf(data.getId());
            tableData[i][2] = data.getStartTime();
            tableData[i][3] = String.valueOf(data.getNotes());
            tableData[i][4] = String.valueOf(data.getFlowRate());
            tableData[i][5] = String.valueOf(data.getValue05());
            tableData[i][6] = String.valueOf(data.getValue10());
            tableData[i][7] = String.valueOf(data.getValue20());
            tableData[i][8] = String.valueOf(data.getValue30());
            tableData[i][9] = String.valueOf(data.getValue50());
            tableData[i][10] = String.valueOf(data.getValue100());
        }
        return tableData;
    }
    //获取点位平均数据
    private String[][] getLoctionStatsTable(List<LocationStats> stats) {
        if (stats == null || stats.isEmpty()) {
            return new String[0][0];
        }
        List<String[]> tableRows = new ArrayList<>();
        for (LocationStats s : stats) {
            String[] row = new String[3];
            row[0] = s.getLocationName();
            row[1] = s.getCount()  + "";
            row[2] = s.getAvg05()  + "";
            tableRows.add(row);
        }
        return tableRows.toArray(new String[0][0]);
    }
    //绘制标题
    private float drawReportTitle(Canvas canvas, float startY,Typeface font ,StdDialogData data ,AvgMeasurementWithMeasurements avg) {
        Paint paint = createPaint(20, Color.BLACK, true);
        paint.setTypeface(font);

        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        float textHeight = fontMetrics.descent - fontMetrics.ascent;
        float textY = startY + paint.getTextSize();
        //居中显示

        String titleText = "标准报告";
        float textWidth = paint.measureText(titleText);

        int pageWidth = canvas.getWidth();
        // 计算居中 X 坐标
        float textX = (pageWidth - textWidth) / 2;
        canvas.drawText(titleText, textX, textY, paint);


        paint.setTextSize(10);
        //标准长度
        textWidth  = paint.measureText(data.getIp());
        textX = (pageWidth - textWidth) / 2;
        canvas.drawText(data.getIp(), textX, textY+15, paint);

        paint.setTextSize(12);
        drawLabelValuePair(canvas, "报告标题", data.getTitle(), 50, textY + 32, paint);
        paint.setTextSize(10);
        drawLabelValuePair(canvas, "证书结果", "无效", 50, textY + 47, paint);
        String dateStr = avg.avgMeasurement.getStartTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(dateStr); // 可能抛出 ParseException
            // 使用 Calendar 增加一分钟
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.MINUTE, 1); // 加1分钟
            // 格式化回字符串
            String newDateStr = sdf.format(calendar.getTime());

            drawLabelValuePair(canvas, "时间范围",dateStr + " ~ " + newDateStr, 50, textY + 62, paint);
        } catch (ParseException e) {
            System.err.println("日期格式错误！请使用 yyyy-MM-dd HH:mm:ss 格式");
            e.printStackTrace();
        }

        drawLabelValuePair(canvas, "用户", avg.user.getName(), 50, textY + 77, paint);

        textY = textY + 100;

        canvas.drawText("洁净室信息", 50, textY, paint);
        canvas.drawText("设备信息", 390, textY, paint);

        paint.setFakeBoldText(false);
        // 用户信息
        drawMultiColumnInfo(canvas,
                new String[]{"区域", "级别", "设备型号"},
                new String[]{avg.location.getName(), data.getLevel(), "A240"},
                50, textY + 12, 170,font);
        drawMultiColumnInfo(canvas,
                new String[]{"群组", "气流", "序列号"},
                new String[]{avg.location.getGroup(), data.getAir(), "A2400074"},
                50, textY + 22, 170,font);
        drawMultiColumnInfo(canvas,
                new String[]{"面积", "状态", "校准时间"},
                new String[]{"30.0m²", data.getStatus(), "2025-04-25"},
                50, textY + 32, 170,font);
        drawMultiColumnInfo(canvas,
                new String[]{"方法", "流速", "设备ID"},
                new String[]{"Default", avg.avgMeasurement.getFlow()  + "LPM", "N/A"},
                50, textY + 42, 170,font);
        // 返回新的Y坐标（标题下方）
       textY =   textY + 20;
        return textY + textHeight + 10; // 加10作为间距
    }
    // 绘制页眉 - 返回新的Y坐标
    private float drawHeader(Context context, Canvas canvas, PdfDocument.PageInfo pageInfo, float startY,Typeface font) {
        Paint paint = createPaint(16, Color.BLACK, true);
        paint.setTypeface(font);

        // 绘制Logo
        Drawable vectorDrawable = ContextCompat.getDrawable(context, R.drawable.logo_svg);
        if (vectorDrawable != null) {
            int desiredWidth = 80;
            int desiredHeight = (int) (desiredWidth * (float) vectorDrawable.getIntrinsicHeight() / vectorDrawable.getIntrinsicWidth());
            int scaleFactor = 2;
            Bitmap bitmap = Bitmap.createBitmap(desiredWidth * scaleFactor, desiredHeight * scaleFactor, Bitmap.Config.ARGB_8888);
            Canvas tempCanvas = new Canvas(bitmap);
            vectorDrawable.setBounds(0, 0, tempCanvas.getWidth(), tempCanvas.getHeight());
            vectorDrawable.draw(tempCanvas);
            canvas.drawBitmap(bitmap,
                    new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()),
                    new Rect(50, 20, 50 + desiredWidth, 20 + desiredHeight),
                    null);
        }

        // 绘制标题文本
        String text = "尘埃粒子计数器";
        float textWidth = paint.measureText(text);
        float textX = pageInfo.getPageWidth() - 50 - textWidth;
        canvas.drawText(text, textX, 25 + paint.getTextSize(), paint);

        // 绘制横线
        float lineY = 5 + paint.getTextSize() + 30;
        canvas.drawLine(50, lineY, pageInfo.getPageWidth() - 50, lineY, paint);

        // 返回新的Y坐标（横线下方）
        return lineY + 10; // 加10作为间距
    }


    //辅助方法：计算列宽总和
    private float sum(float[] array) {
        float total = 0;
        for (float value : array) {
            total += value;
        }
        return total;
    }

    // 辅助方法：创建Paint对象
    private Paint createPaint(float textSize, int color, boolean isBold) {
        Paint paint = new Paint();
        paint.setColor(color);
        paint.setTextSize(textSize);
        paint.setFakeBoldText(isBold);
        return paint;
    }

    // 辅助方法：绘制标签-值对
    private void drawLabelValuePair(Canvas canvas, String label, String value, float x, float y, Paint paint) {
        canvas.drawText(label, x, y, paint);
        boolean wasBold = paint.isFakeBoldText();
        paint.setFakeBoldText(false);
        canvas.drawText(value, 130, y, paint);
        paint.setFakeBoldText(wasBold);
    }

    // 辅助方法：绘制多列信息
    private void drawMultiColumnInfo(Canvas canvas, String[] labels, String[] values, float startX, float startY, float columnWidth,Typeface font) {
        Paint paint = createPaint(8, Color.BLACK, false);
        paint.setTypeface(font);

        for (int i = 0; i < labels.length; i++) {
            canvas.drawText(labels[i], startX + (i * columnWidth), startY, paint);
            canvas.drawText(values[i],
                    startX + (i * columnWidth) + paint.measureText("测试记录" + "            "),
                    startY, paint);
        }
    }
    public interface OnPDFGeneratedListener {
        void onSuccess(File file);
        void onError(Exception e);
    }
}
